package com.syslog.entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.annotation.JsonFormat;

@Entity
@Table(name="t_syslog")
public class Syslog {
	private Long id;
	private String description;
	private String staffName;
	private Date time;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}
	
	public String getDescription() {
		return description;
	}	
	public String getStaffName() {
		return staffName;
	}
	
	@JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss",timezone = "GMT+8")
	public Date getTime() {
		return time;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public void setStaffName(String staffName) {
		this.staffName = staffName;
	}

	public void setTime(Date time) {
		this.time = time;
	}

	public static Specification<Syslog> getSpecification( final Syslog syslog)
	{
		Specification<Syslog> spec = new Specification<Syslog>() {
			public Predicate toPredicate(Root<Syslog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//1.Predicate查询条件集合
				 List<Predicate> list = new ArrayList<Predicate>(); 
				 
				//2.根据 QueryDTO数据字段的值进行判断以及条件的组装
				 if(null != syslog && !StringUtils.isEmpty(syslog.getStaffName())) {
					 Predicate  p1 =  cb.like(root.get("staffName").as(String.class),"%"+ syslog.getStaffName()+ "%");
					 list.add(p1);
				 }
				 if(null != syslog && !StringUtils.isEmpty(syslog.getDescription())) {
					 Predicate  p2 =  cb.like(root.get("description").as(String.class),"%"+ syslog.getDescription()+ "%");
					 list.add(p2);
				 }
				 if(null != syslog && !StringUtils.isEmpty(syslog.getTime())) {
					 Predicate  p3 =  cb.like(root.get("time").as(String.class),"%"+ syslog.getTime()+ "%");
					 list.add(p3);
				 }
				 //3.Predicate查询条件集合的 size 创建对应的Predicate查询条件数组
				 Predicate[] p = new Predicate[list.size()];  
				 //4.CriteriaBuilder的and 函数组装 查询条件数组
				 return cb.and(list.toArray(p));  
			}
		};
		return spec;	
	}
}
